<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>平台管理系统</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet"href="/css/plat-style.css">
</head>
<body>

<div class="layui-tab" style="background-color: white">
    <ul class="layui-tab-title">
        <li class="layui-this">基本信息</li>
        <li>属性</li>
        <li>详情</li>
    </ul>
    <div class="layui-tab-content">
        <%--基本信息--%>
        <div class="layui-tab-item layui-show">
            <div class="layui-form-item" style="width:50%">
                <label class="layui-form-label">贷款名称:</label>
                <div class="layui-input-block">
                    <input type="text" name="loanName" id="loanName" lay-verify="title" autocomplete="off" placeholder="请输入贷款名称" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" style="width: 50%">
                <label class="layui-form-label">是否启用:</label>
                <div class="layui-input-block">
                    <select class="layui-input" id="status">
                        <option value="1">启用</option>
                        <option value="2">禁用</option>
                    </select>
                </div>
            </div>
        </div>
        <%--属性--%>
        <div class="layui-tab-item" style="margin-top: 20px">
            <div class="layui-col-sm9" style=" line-height: 25px; font-size: large;">
                如果添加的属性为：<i style="color: red">单选、复选、下拉框，属性值格式为：xx,xx(英文逗号)，其他属性值可为空。</i>
            </div>
            <table class="layui-table" id="table" lay-filter="table">
                <thead>
                <tr>
                    <td>属性类型</td>
                    <td>属性名</td>
                    <td>属性值</td>
                    <td>排序</td>
                    <td>操作</td>
                </tr>
                </thead>
                <tbody></tbody>
            </table>
            <div style="text-align: center"> <a class="layui-btn layui-btn-xs add" style="width: 100px;height: 30px;margin-top: 20px">添加</a></div>
        </div>
        <%--详情--%>
        <div  class="layui-tab-item">
            <div class="layui-col-sm12">
                                    <textarea id="content" name="content"
                                              style="display: none">${business.content}</textarea>
                <script id="articleEditor" type="text/plain"
                        style="width:100%;height:400px;"></script>
            </div>
        </div>
    </div>
</div>

<%--操作--%>
<div class="layui-form-item layui-layout-admin">
    <div class="layui-col-sm4">
        <div class="layui-footer" style="left: 0;">
            <button type="button" class="layui-btn layui-btn-normal" id="saveBtn">保存</button>
            <a href="/bankloan/list" class="layui-btn" style="margin-left: 10px">取消</a>
        </div>
    </div>
</div>


<script src="/layuiadmin/layui/layui.js"></script>
<script type="text/javascript" src="/js/jquery/jquery.min.js"></script>
<script type="text/javascript" src="/js/common.js"></script>
<script type="text/javascript" src="/js/jquery.form.js"></script>
<script type="text/javascript" src="/js/plugins/image/previewImg.js"></script>
<script type="text/javascript" src="/js/plugins/dropzone/dropzone.js"></script>
<script type="text/javascript" src="/js/plugins/layui-formSelect/formSelects-v4.min.js"></script>
<script type="text/javascript" src="/js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="/js/ueditor/ueditor.all.min.js"></script>
<script type="text/javascript" src="/js/ueditor/lang/zh-cn/zh-cn.js"></script>
<script>
    layui.config({
        base: '/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form','upload'], function(){
        var $ = layui.$,
            form = layui.form,
            element = layui.element,
            layer = layui.layer;
        form.render('select');
        element.render();

        var active = {
            editThis: function (id) {
                layer.open({
                    title:'新增/编辑首页版块',
                    type: 2,
                    area: ['500px', '350px'],
                    content: '/app/appHomeEdit?id='+id
                });
            },
            showThis:function (id,modelType) {
                //商品推荐
                if(modelType==1){
                    window.location.href = "/app/recommend?parentId="+id;
                }
                //每日必逛
                if(modelType==2){
                    window.location.href = "/app/daily?parentId="+id;
                }
            },
            updateThis:function (id, display,url) {
                layer.confirm('确定操作吗?',function () {
                    $.ajax({
                        url: url,
                        data: {'id': id, "display": display},
                        dataType: "json",
                        type: "post",
                        success: function (data) {
                            if (data.status) {
                                layer.msg(data.desc);
                                setTimeout(function () {
                                    window.location.reload();
                                }, 1000)
                            } else {
                                layer.msg(data.desc);
                            }
                        }
                    })
                })
            }
        };
        //编辑版块信息
        $('.editThis').on('click', function(){
            var id = $(this).data('id');
            var type = 'editThis';
            active[type] && active[type].call(this,id);
        });
        //显示版块内容
        $('.showThis').on('click',function () {
            var id = $(this).data('id');
            var modelType = $(this).data('model');
            var type = $(this).data('type');
            active[type] && active[type].call(this,id,modelType);
        });
        //显示隐藏
        $('.updateThis').on('click',function () {
            var id = $(this).data('id');
            var type = $(this).data('type');
            var display = $(this).data('display');
            var url = "/app/handleAppHomeDisplay";
            active[type] && active[type].call(this,id,display,url);
        });
    });

    layui.use('element', function(){
        var $ = layui.jquery
            ,element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块

        //触发事件
        var active = {
            tabAdd: function(){
                //新增一个Tab项
                element.tabAdd('demo', {
                    title: '新选项'+ (Math.random()*1000|0) //用于演示
                    ,content: '内容'+ (Math.random()*1000|0)
                    ,id: new Date().getTime() //实际使用一般是规定好的id，这里以时间戳模拟下
                })
            }
            ,tabDelete: function(othis){
                //删除指定Tab项
                element.tabDelete('demo', '44'); //删除：“商品管理”


                othis.addClass('layui-btn-disabled');
            }
            ,tabChange: function(){
                //切换到指定Tab项
                element.tabChange('demo', '22'); //切换到：用户管理
            }
        };

        $('.site-demo-active').on('click', function(){
            var othis = $(this), type = othis.data('type');
            active[type] ? active[type].call(this, othis) : '';
        });

        //Hash地址的定位
        var layid = location.hash.replace(/^#test=/, '');
        element.tabChange('test', layid);

        element.on('tab(test)', function(elem){
            location.hash = 'test='+ $(this).attr('lay-id');
        });

    });
    var sortNum=0;
    var inputTypeHtml=`<td>`+
       `<select class="layui-input" name="inputType">`+
           `<option value="1">单选按钮</option>`+
           `<option value="2">复选框</option>`+
           `<option value="3">下拉框</option>`+
           `<option value="4">输入框</option>`+
           `<option value="5">日期选项</option>`+
           `<option value="6">手机号</option>`+
           `<option value="7">省市县区</option>`+
           `<option value="8">身份证</option>`+
           `<option value="9">邮箱</option>`+
      `</select>`+
      `</td>`
    //因为动态添加的元素class属性是无效的，所以不能用$('.add').click(function(){});
    $('body').on('click', '.add', function() {
        var fieldMe=document.getElementsByName("fieldName");
        var inputType=document.getElementsByName("inputType");
        var inputValue=document.getElementsByName("inputValue");
        for (var i = 0; i <fieldMe.length ; i++) {
            if( fieldMe[i].value==''){
                layer.msg('属性名不能为空', {
                    time : 2000
                });
                return;
            }
            var sel=inputType[i];
            var index = sel.selectedIndex; // 选中索引
            var value = sel.options[index].value; // 选中值
            if(value!=4){
                var str=inputValue[i].value;
                // if(!/^\w+(\,\w+)*$/.test(str)){
                //     inputValue[i].style.border="1px solid red";
                //     layer.msg('属性值格式不正确。', {
                //         time : 2000
                //     });
                //     return;
                // }else {
                //     inputValue[i].style.border="1px solid #d9edf7";
                // }
            }
        }
        sortNum=sortNum+1;
        //你要添加的html
        var html = '<tr>'+
             inputTypeHtml+
            '<td><input type="text" class="layui-input" name="fieldName"></td>'+
            '<td><input type="text" class="layui-input" name="inputValue"></td>'+
            '<td><input type="text" class="layui-input" value='+sortNum+' name="sort" ></td>'+
            '<td>'+
            '<a class="layui-btn layui-btn-danger layui-btn-xs del">删除</a>'+
            '</td>'+
            '</tr>';
        //添加到表格最后
        $(html).appendTo($('#table tbody:last'));
    });
    $('body').on('click', '.del', function() {
        if ($('#table tbody tr').length === 1) {
            layer.msg('只有一条不允许删除。', {
                time : 2000
            });
        } else {
            //删除当前按钮所在的tr
            $(this).closest('tr').remove();
            sortNum=sortNum-1;
        }
    });

    var fiedArr={
        bankLoan:{
            "loanName":"",
            "status":"",
            "loanDetails":""
        },
        "bankLoanFieldMaintainSubs":[],
    };
    $("#saveBtn").click(function(){
        //基本信息
        var loanName=$('#loanName').val();
        if(loanName==''){
            layer.msg('贷款名称不能为空。', {
                time : 2000
            });
            return;
        }

        fiedArr.bankLoan.loanName=loanName;
        //属性信息
        fiedArr.bankLoanFieldMaintainSubs=[];
        //详情
        var loanDetails=UE.getEditor('articleEditor').getContent();
        fiedArr.bankLoan.loanDetails=loanDetails;
        var fiedName=document.getElementsByName("fieldName") ;
        var inputType=document.getElementsByName("inputType");
        var inputValue=document.getElementsByName("inputValue");
        var sort=document.getElementsByName("sort");
        for (var i = 0; i <fiedName.length ; i++) {
            if(fiedName[i].value==''){
                fiedName[i].style.border="1px solid red";
                layer.msg('属性名不能为空！。', {
                    time : 2000
                });
                return;
            }
            var sel=inputType[i];
            var index = sel.selectedIndex; // 选中索引
            var value = sel.options[index].value; // 选中值
            // if(value!=4){
            //     if(!/^\w+(\,\w+)*$/.test(inputValue[i].value)){
            //         inputValue[i].style.border="1px solid red";
            //         layer.msg('属性值格式不正确。', {
            //             time : 2000
            //         });
            //         return;
            //     }
            // }
            fiedArr.bankLoanFieldMaintainSubs.push({"fieldName":fiedName[i].value,"sort":sort[i].value,"inputType":inputType[i].value,"inputValue":inputValue[i].value});
        }
        $.ajax({
            url: "/bankloan/saveDate",
            data: JSON.stringify(fiedArr),
            dataType:'application/json',
            headers: {
                "Content-Type": "application/json",
            },
            type: "post",
            success: function (data) {
                console.info("xxxxxxxxxxxxxxxxxxx")
                console.info(data);
                window.location.href="/bankloan/listDate"
            },error:function (data) {
                console.info("ggggggggggggggggggggg")
                console.info(data);
            }
        })
        window.location.href="/bankloan/list"
    });



    /* 富文本编辑器加载 */
    $(function () {
        /* 富文本编辑器加载 */
        var ue = UE.getEditor('articleEditor');
        UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
        UE.Editor.prototype.getActionUrl = function (action) {
            if (action == '/uploadFile') {
                return '/file/editorupload';

            } else {
                return this._bkGetActionUrl.call(this, action);
            }
        };
        UE.getEditor('articleEditor').ready(function () {
            UE.getEditor('articleEditor').setContent($("#content").text());
        });
        // layui多选插件加载
        var formSelects = layui.formSelects;
        formSelects.value('label');
    });


    $("#dropz").dropzone({
        url: "/file/editorupload",
        maxFiles: 3,
        maxFilesize: 5,
        acceptedFiles: ".gif,.jpg,.png,.jpeg",
        addRemoveLinks: true,
        dictDefaultMessage: "点击或者拖拽文件以上传",
        init: function () {
            this.emit("initimage", "${business.coverUrl}", "${business.coverUrl}");
            this.on("success", function (file, data) {
                var url = file.previewElement.classList[3];
                $("#imgDiv").append('<input type="text" name="urls" value="' + url + '"/> ');
                $("#allUrl").append('<input type="text" name="urls" value="' + url + '"/> ');
            });
            this.on("removedfile", function (file) {
                var url = file.previewElement.classList[3];
                $("#imgDiv").find("input").each(function (e) {
                    var val = $(this).val();
                    if (url == val) {
                        $(this).remove();
                    }
                });
                $("#allUrl").find("input").each(function (e) {
                    var val = $(this).val();
                    if (url == val) {
                        $(this).remove();
                    }
                });
            });
        }
    });

    function saveBusinessFile() {
        alert(111);
        $("#pcContent").text(UE.getEditor('articleEditor').getContent());
        $("#businessFileForm").ajaxSubmit({
            type: 'post',
            url: "/file/editorupload",
            data: $("#businessFileForm").serialize(),
            dataType: 'json',
            success: function (data) {
                if (data.status) {
                    for (var key in data.data) {
                        $("#" + key).val(data.data[key]);
                    }
                    saveBusinessEdit();
                } else {
                    layer.msg(data.desc, {icon: 2});
                }
            },
            error: function () {
                layer.msg("图片上传失败", {icon: 2});
            }
        })
    }

</script>
</body>
</html>